package com.sk.coin.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.sk.coin.feign.JwtToken;
import com.sk.coin.feign.OAuth2FeighClient;
import com.sk.coin.sys.dto.LoginResult;
import com.sk.coin.sys.entity.SysMenu;
import com.sk.coin.sys.service.ISysMenuService;
import com.sk.coin.sys.service.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: SongKun
 * @date: 2022/2/23
 * @Description:
 */
@Service
@Slf4j
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private OAuth2FeighClient oAuth2FeighClient;

    @Autowired
    private ISysMenuService sysMenuService;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public LoginResult login(String username, String password) {
        log.info("用户{}开始登陆",username);
        // 1.获取token需要远程调用authorization-server服务
        ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeighClient
                .getToken("password", username, password, "admin_type", basicToken);
        if(tokenResponseEntity == null || tokenResponseEntity.getStatusCode() != HttpStatus.OK
                || tokenResponseEntity.getBody() == null) {
            throw new ApiException(ApiErrorCode.FAILED);
        }
        JwtToken jwtToken = tokenResponseEntity.getBody();
        log.info("远程调用授权服务器成功，获取的token为{}", JSON.toJSONString(jwtToken,true));
        String token = jwtToken.getAccessToken();
        // 2.查询菜单数据
        Jwt jwt = JwtHelper.decode(token);
        String jwtJsonStr = jwt.getClaims();
        JSONObject jwtJson = JSON.parseObject(jwtJsonStr);
        Long userId = Long.valueOf(jwtJson.getString("user_name"));
        List<SysMenu> menus = sysMenuService.getMenuByUserId(userId);
        // 3.从jwt中获取权限
        JSONArray authoritiesJsonArray = jwtJson.getJSONArray("authorities");
        List<SimpleGrantedAuthority> authorities = authoritiesJsonArray.stream()
                .map(item -> new SimpleGrantedAuthority(item.toString()))
                .collect(Collectors.toList());
        // 4.token存入redis
        redisTemplate.opsForValue().set(token,"",jwtToken.getExpiresIn(), TimeUnit.SECONDS);
        // token前面有bearer
        return new LoginResult(jwtToken.getTokenType() + " " + token,menus,authorities);
    }
}
